package com.cyf.service.impl;

import com.cyf.activemq.network.bean.MqBusinessOpt;
import com.cyf.activemq.network.bean.MqCancelBookingReq;
import com.cyf.activemq.service.SendMsgService;
import com.cyf.db.bean.User;
import com.cyf.db.bean.BookingInfo;
import com.cyf.db.mapper.UserMapper;
import com.cyf.db.mapper.BookingInfoMapper;
import com.cyf.db.mapper.EbRecordMapper;
import com.cyf.db.mapper.ParkingLockInfoMapper;
import com.cyf.service.BookingService;
import com.cyf.util.DateUtil;
import com.cyf.util.ObjectMapperUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 车位预约
 * Created by hfy on 2017/5/4.
 */
@Service
public class BookingServiceImpl implements BookingService {

    private static final Logger logger = LoggerFactory.getLogger(BookingServiceImpl.class);


    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EbRecordMapper ebRecordMapper;
    @Autowired
    private BookingInfoMapper bookingInfoMapper;
    @Autowired
    private ParkingLockInfoMapper parkingLockInfoMapper;
    @Autowired
    private SendMsgService sendMsgService;

    @Override
    @Transactional
    public void timeout(Date now) {
        List<BookingInfo> bookingInfos = bookingInfoMapper.getTimeOut(now);
        if (bookingInfos != null) {
            for (BookingInfo bookingInfo : bookingInfos) {
                User user = userMapper.getById(bookingInfo.getAppUserId());
                if (user == null) {
                    logger.error("预约订单({})中的app用户({})不存在！", bookingInfo.getId(), bookingInfo.getAppUserId());
                    continue;
                }
                cacelBooking(bookingInfo, user);
            }
        }
    }

    @Override
    @Transactional
    public void cacelBooking(BookingInfo bookingInfo, User user) {
        // 更新数据库
        // 1、更新车位预约信息
        Date endTime = new Date();
        bookingInfoMapper.updateStatusAndEndTimeById(bookingInfo.getId(), BookingInfo.BOOKINGSTATUS_FAILURE, endTime);
        // 2、更新地锁信息 预约状态和锁定状态
        parkingLockInfoMapper.cacelBooking(bookingInfo.getParkingLockId());
        // 3、更新eb余额
//        int ebBalance = appUser.getEbBalance() == null ? 0 : appUser.getEbBalance();
//        appUserMapper.updateEb(ebBalance - bookingInfo.getFee(), appUser.getId());
        // 4、保存eb消费记录
//        EbRecord ebRecord = new EbRecord();
//        ebRecord.setBookingId(bookingInfo.getId());
//        ebRecord.setCreatedTime(endTime);
//        ebRecord.setOldFee(ebBalance);
//        ebRecord.setFee(bookingInfo.getFee());
//        ebRecord.setNewFee(ebBalance - bookingInfo.getFee());
//        ebRecordMapper.insertEbRecord(ebRecord);

        // 如果预约信息已经发送车场，更新发送状态
        if (bookingInfo.getSendToParking() == 1) {
            bookingInfoMapper.updateSendById(bookingInfo.getId(), BookingInfo.SEND_CANCELBOOKING);
        }

        // TOC->TOB->PMSVR
        try {
            MqCancelBookingReq mqCancelBookingReq = new MqCancelBookingReq();
            mqCancelBookingReq.setOptid(MqBusinessOpt.CANCEL_BOOKING);
            mqCancelBookingReq.setUuid(UUID.randomUUID().toString());
            mqCancelBookingReq.setBookingId(bookingInfo.getId());
            mqCancelBookingReq.setParkingId(bookingInfo.getParkingId());
            mqCancelBookingReq.setEndTime(DateUtil.formatDate(endTime, MqCancelBookingReq.PATTERN_ENDTIME));
            sendMsgService.sendQueueMessageText(ObjectMapperUtils.getObjectMapper().writeValueAsString(mqCancelBookingReq));
        }catch (Exception e) {
            logger.error("取消车位预约，发送TOC异常：{}", e);
        }
    }
}
